<?php

require_once( 'AbstractDatasource.php' );

// TODO: Something to define the requirements?  DTD? - You know, I'd love to generate one, but it doesn't look likely with this structure

class XmlDatasource extends AbstractDatasource {

	function XmlDatasource( $oXmlDocument ) {
		$this->AbstractDatasource();
		$this->oXmlDocument = $oXmlDocument;
		$this->iLastDdl     = time();
	}

	function _GetTableListFromXmlDoc() {
		$oTableElements = null;
		XmlSearcher::GetElements( $oTableElements, $this->oXmlDocument, array( 'TABLE_LIST', 'TABLE' ) );
		return $oTableElements;
	}
	
	function _GetForeignKeyListFromXmlDoc() {
		$oForeignKeyElements = null;
		XmlSearcher::GetElements( $oForeignKeyElements, $this->oXmlDocument, array( 'FOREIGN_KEY' ) );
		return $oForeignKeyElements;
	}
	
	function GetTableList() {
		$oTableElements = $this->_GetTableListFromXmlDoc();

		return $oTableElements->ReturnArrayFromCallback( 'GetAttribute', 'NAME' );
	}
	
	function _GetColumnsFromTable( $oXmlTableElement ) {
		$oColumnElements = null;
		XmlSearcher::GetElements( $oColumnElements, $oXmlTableElement, array( 'Column' ) );
		return $oColumnElements->ReturnArrayFromCallback( 'GetAllAttributesAsAssociativeArray' );
	}

	function GetColumnList( $sTableName ) {
		return $this->_GetColumnsFromTable( XmlSearcher::GetElementWithAttribute( $this->_GetTableListFromXmlDoc(), 'Name', $sTableName ) );
	}
	
	function _GetColumnsArrayFromKey( $oKey, $sColumnElementName ) {
		
		$oColumnElements = null;
		XmlSearcher::GetElements( $oColumnElements, $oKey, array( $sColumnElementName ) );
		return $oColumnElements->ReturnArrayFromCallback( 'GetAttribute', 'COLUMN_NAME' );
	}
	
	function GetForeignKeys( $sTableName ) {
	
		$oAllForeignKeys = $this->_GetForeignKeyListFromXmlDoc();
		
		$oThisTablesKeys = null;
		XmlSearcher::GetElementsWithAttribute( $oThisTablesKeys, $oAllForeignKeys, 'FROM_TABLE', $sTableName );
		XmlSearcher::GetElementsWithAttribute( $oThisTablesKeys, $oAllForeignKeys, 'TO_TABLE'  , $sTableName );

		$iIndex = 0;
		$aKeys  = array();
		$oThisTablesKeys->RewindElementIterator();
		while( $oThisTablesKeys->HasAnotherElement() ) {
			$oThisKey = $oThisTablesKeys->GetNextElement();
			$aKeys[++$iIndex] = $oThisKey->GetAllAttributesAsAssociativeArray();
			$aKeys[$iIndex]['FROM_COLUMNS'] = $this->_GetColumnsArrayFromKey( $oThisKey, 'FOREIGN_KEY_COLUMN' );
		}
		
		return $aKeys;
	}
	
	function GetPrimaryKey( $sTableName ) {

		$oTableElement   = XmlSearcher::GetElementWithAttribute( $this->_GetTableListFromXmlDoc(), 'Name', $sTableName );
		$oKeyElement     = XmlSearcher::GetElementByName( $oTableElement, 'PRIMARY_KEY' );

		$aKey['NAME']    = $oKeyElement->GetAttribute('NAME');
		$aKey['COLUMNS'] = $this->_GetColumnsArrayFromKey( $oKeyElement, 'PRIMARY_KEY_COLUMN' );

		return $aKey;

	}
	
	function GetDatasourceId() {
		return $this->oXmlDocument->GetName();
	}
}

?>
